import { routes } from '@/router'

import React, { useCallback, useEffect, useState } from 'react'

import type { MenuProps } from 'antd'
import { Menu } from 'antd'
import { useNavigate } from 'react-router-dom'
import menuStyle from './AigcMenu.module.scss'

type MenuItem = Required<MenuProps>['items'][number]

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type
  } as MenuItem
}

function getItems(items: any) {
  let menuItems: MenuItem[] = []

  function itemIterator(items: any, parentPath?: string) {
    parentPath = parentPath ? parentPath : ''
    const resultItem: MenuItem[] = []
    for (let i = 0; i < items.length; i++) {
      const item = items[i]

      const childItem: MenuItem[] = []

      if (item.children && item.children.length > 0) {
        childItem.push(...itemIterator(item.children, item.path))
      }

      if (item.handle.isShow) {
        if (item.children && item.children.length > 0) {
          resultItem.push(
            getItem(
              item.handle.name,
              parentPath + '/' + item.path,
              item.handle.icon,
              childItem
            )
          )
        } else {
          resultItem.push(
            getItem(
              item.handle.name,
              parentPath + '/' + item.path,
              item.handle.icon
            )
          )
        }
      }
    }
    return resultItem
  }
  menuItems = itemIterator(items)
  // menuItems.concat();
  // console.log('menuItems', menuItems)

  return menuItems
}

export default function AigcMenu() {
  const [menuList, setMenuList] = useState<MenuProps['items']>([])
  useEffect(() => {
    setMenuList(getItems(routes[0].children))
  }, [])

  const navigate = useNavigate()
  type MenuClickType = MenuProps['onClick']
  const onClick: MenuClickType = useCallback((e: any) => {
    // console.log(e.item.label)
    navigate(e.key, {})
  }, [])
  return (
    <>
      <Menu
        onClick={onClick}
        className={menuStyle.menu}
        defaultSelectedKeys={['/home']}
        mode="inline"
        items={menuList}
      />
    </>
  )
}
